<template>
  <div id="login">
    <div class="login-warp">
      <ul class="menu-tab">
        <li v-for="item in menuTab" :key="item.id" :class="{'current': item.current}" @click="toggleMenu(item)">{{item.txt}}</li>
      </ul>
      <!--表单的开始-->
      <el-form :model="ruleForm" status-icon :rules="rules" ref="loginForm" class="login-form" size="medium">
        <el-form-item prop="username" class="item-form">
          <label>邮箱</label>
          <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item prop="password" class="item-form">
          <label>密码</label>
          <el-input type="password" v-model="ruleForm.password" autocomplete="off" minlength="6" maxlength="20"></el-input>
        </el-form-item>

        <el-form-item prop="passwords" class="item-form" v-show="model === 'register'">
          <label>重复密码</label>
          <el-input type="password" v-model="ruleForm.passwords" autocomplete="off" minlength="6" maxlength="20"></el-input>
        </el-form-item>

        <el-form-item prop="code" class="item-form">
          <label>验证码</label>
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input type="text" v-model="ruleForm.code" minlength="6" maxlength="6"></el-input>
            </el-col>
            <el-col :span="9">
              <el-button type="success" class="black" @click="getSms()" :disabled=codeButtonStatus.status>{{ codeButtonStatus.text }}</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            @click="submitForm('loginForm')"
            class="login-btn black"
            :disabled=loginButtonStatus
          >{{ model === 'login' ? '登录' : '注册' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import sha1 from 'js-sha1'
import { stripscript, validatePass, validateEmail, validateVCode } from '@/utils/validate'
import { reactive, ref, onMounted } from '@vue/composition-api'
import { GetSms, Register } from '@/api/login'
export default {
  name: 'Login',
  setup (props, { refs, root }) {
    // 验证用户名
    let validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (validateEmail(value)) {
        callback(new Error('用户名格式有误'))
      } else {
        callback()
      }
    }
    // 验证密码
    let validatePassword = (rule, value, callback) => {
      // 过滤后的数据
      ruleForm.password = stripscript(value)
      value = ruleForm.password
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (validatePass(value)) {
        callback(new Error('密码为6至20位数字+字母'))
      } else {
        callback()
      }
    }
    // 验证重复密码
    let validatePasswords = (rule, value, callback) => {
      // 如果模块值为login, 直接通过
      if (model.value === 'login') { callback() }
      // 过滤后的数据
      ruleForm.passwords = stripscript(value)
      value = ruleForm.passwords
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== ruleForm.password) {
        callback(new Error('重复密码不正确'))
      } else {
        callback()
      }
    }
    // 验证验证码
    let validateCode = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入验证码'))
      } else if (validateVCode(value)) {
        return callback(new Error('验证码格式有误'))
      } else {
        callback()
      }
    }
    const menuTab = reactive([
      { txt: '登录', current: true, type: 'login' },
      { txt: '注册', current: false, type: 'register' }
    ])
    const model = ref('login')
    // 按钮状态
    const loginButtonStatus = ref(true)
    const codeButtonStatus = reactive(
      { status: false,
        text: '获取验证码'
      }
    )
    // 倒计时
    const timer = ref(null)
    // 表单绑定数据
    const ruleForm = reactive({
      username: '',
      password: '',
      passwords: '',
      code: ''
    })
    // 表单的验证
    const rules = reactive({
      username: [
        { validator: validateUsername, trigger: 'blur' }
      ],
      password: [
        { validator: validatePassword, trigger: 'blur' }
      ],
      passwords: [
        { validator: validatePasswords, trigger: 'blur' }
      ],
      code: [
        { validator: validateCode, trigger: 'blur' }
      ]
    })
    /**
     * 声明函数
     */
    // 切换模块
    const toggleMenu = (data => {
      menuTab.forEach((elem) => {
        elem.current = false
      })
      // 高光
      data.current = true
      // 修改模块值
      model.value = data.type
      // 重置表单
      // this.$refs[formName].resetFields()
      resetFromData()
      clearCountDown()
    })
    // 清除表单数据
    const resetFromData = (() => {
      refs.loginForm.resetFields()
    })
    // 更新按钮状态
    const updateButtonStatus = ((params) => {
      codeButtonStatus.status = params.status
      codeButtonStatus.text = params.text
    })
    /**
     * 获取验证码
     */
    const getSms = (() => {
      // 验证数据
      if (ruleForm.username == '') {
        root.$message.error('邮箱不能为空！！！')
        return false
      }
      if (validateEmail(ruleForm.username)) {
        root.$message.error('邮箱格式有误，请重新输入！！！')
        return false
      }
      updateButtonStatus({
        status: true,
        text: '发送中'
      })
      // 请求接口
      let requestData = {
        username: ruleForm.username,
        module: model.value
      }
      GetSms(requestData).then(response => {
        let data = response.data
        root.$message({
          showClose: true,
          message: data.message,
          type: 'success'
        })
        // 启用登录或注册按钮
        loginButtonStatus.value = false
        countDown(60)
      }).catch(error => {
        console.log(error)
      })
    })
    /**
     * 提交表单
     */
    const submitForm = (formName => {
      refs[formName].validate((valid) => {
        if (valid) {
          console.log(model.value)
          model.value === 'login' ? login() : register()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    })
    /**
     * 注册
     */
    const register = (() => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
        module: 'register'
      }
      Register(requestData).then(response => {
        let data = response.data
        root.$message({
          showClose: true,
          message: data.message,
          type: 'success'
        })
        toggleMenu(menuTab[0])
        clearCountDown()
      }).catch(error => {

      })
    })
    /**
     * 登录
     */
    const login = (() => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code
      }
      root.$store.dispatch('app/login', requestData).then(response => {
        // 页面跳转
        root.$router.push({
          name: 'Home'
        })
      }).catch(error => {})
    })
    /**
     * 倒计时
     */
    const countDown = ((number) => {
      // 判断定时器是否存在，存在则清除
      if (timer.value) {
        clearInterval(timer.value)
      }
      let time = number
      timer.value = setInterval(() => {
        time--
        if (time === 0) {
          clearInterval(timer.value)
          updateButtonStatus({
            status: false,
            text: '重新发送'
          })
        } else {
          codeButtonStatus.text = `倒计时${time}秒`
        }
      }, 1000)
    })
    /**
     * 清除倒计时
     */
    const clearCountDown = (() => {
      updateButtonStatus(codeButtonStatus)
      clearInterval(timer.value)
    })
    /**
     * 生命周期
     */
    // 挂载完成后
    onMounted(() => {
    })
    return {
      menuTab,
      model,
      loginButtonStatus,
      codeButtonStatus,
      updateButtonStatus,
      ruleForm,
      rules,
      toggleMenu,
      resetFromData,
      clearCountDown,
      getSms,
      submitForm,
      login,
      register
    }
  }
}
</script>

<style lang="scss" scoped>
#login {
  height: 100vh;
  background-color: #344a5f;
}
.login-warp {
  width: 330px;
  margin: auto;
}
.menu-tab {
  margin: 0;
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
  .current {
    background-color: rgba(0, 0, 0, 0.1);
  }
}
.login-form {
  margin-top: 29px;
  label {
    display: block;
    margin-bottom: 3px;
    font-size: 14px;
    color: #fff;
  }
  .item-form {
    margin-bottom: 13px;
  }
  .black {
    display: block;
    width: 100%;
  }
  .login-btn {
    margin-top: 19px;
  }
}
</style>
